package com.tanhua.sso.controller;

import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户使用验证码登录
     *
     * @param param JSON格式的手机号
     * @return ResponseEntity:Token + isNew
     */
    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) {
        try {
            String phone = param.get("phone");
            String verificationCode = param.get("verificationCode");

            Map<String, String> dataMap = userService.login(phone, verificationCode);

            //如果能获取到dataMap,表示登录成功,那么就解析dataMap封装成ResponseEntity
            if (null != dataMap && !dataMap.isEmpty()) {
                HashMap<String, Object> result = new HashMap<>(2);
                result.put("token", dataMap.get("token"));
                result.put("isNew", Boolean.valueOf(dataMap.get("isNew")));
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登录失败!").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    /**
     * 校验token，根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }
}
